package model

import (
	"context"
	"database/sql"
	"time"

	"golang.org/x/crypto/bcrypt"
)

type User struct {
	ID         int       `json:"id"`
	Username   string    `json:"username"`
	Password   string    `json:"-"` // 不输出密码
	Email      string    `json:"email"`
	Status     int       `json:"status"`
	CreateTime time.Time `json:"create_time"`
	UpdateTime time.Time `json:"update_time"`
}

type UserModel struct {
	db *sql.DB
}

func NewUserModel(db *sql.DB) *UserModel {
	return &UserModel{db: db}
}

// CreateUser 创建用户
func (m *UserModel) CreateUser(ctx context.Context, user *User) error {
	// 加密密码
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}

	// 插入用户
	result, err := m.db.ExecContext(ctx, `
		INSERT INTO wqyf_users (username, password, email, status)
		VALUES (?, ?, ?, ?)
	`, user.Username, string(hashedPassword), user.Email, user.Status)
	if err != nil {
		return err
	}

	id, err := result.LastInsertId()
	if err != nil {
		return err
	}
	user.ID = int(id)

	return nil
}

// ValidateUser 验证用户密码
func (m *UserModel) ValidateUser(ctx context.Context, username, password string) (*User, error) {
	user := &User{}
	err := m.db.QueryRowContext(ctx, `
		SELECT id, username, password, email, status, create_time, update_time
		FROM wqyf_users
		WHERE username = ?
	`, username).Scan(
		&user.ID,
		&user.Username,
		&user.Password,
		&user.Email,
		&user.Status,
		&user.CreateTime,
		&user.UpdateTime,
	)

	if err != nil {
		return nil, err
	}

	// 验证密码
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		return nil, err
	}

	return user, nil
}

// GetUserByID 根据ID获取用户
func (m *UserModel) GetUserByID(ctx context.Context, id int) (*User, error) {
	user := &User{}
	err := m.db.QueryRowContext(ctx, `
		SELECT id, username, email, status, create_time, update_time
		FROM wqyf_users
		WHERE id = ?
	`, id).Scan(
		&user.ID,
		&user.Username,
		&user.Email,
		&user.Status,
		&user.CreateTime,
		&user.UpdateTime,
	)

	if err != nil {
		return nil, err
	}

	return user, nil
}

// UpdateUser 更新用户信息
func (m *UserModel) UpdateUser(ctx context.Context, user *User) error {
	_, err := m.db.ExecContext(ctx, `
		UPDATE wqyf_users 
		SET email = ?, status = ?
		WHERE id = ?
	`, user.Email, user.Status, user.ID)
	return err
}

// UpdatePassword 更新用户密码
func (m *UserModel) UpdatePassword(ctx context.Context, userID int, newPassword string) error {
	// 加密新密码
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
	if err != nil {
		return err
	}

	_, err = m.db.ExecContext(ctx, `
		UPDATE wqyf_users 
		SET password = ?
		WHERE id = ?
	`, string(hashedPassword), userID)
	return err
} 